<template>
  <canvas ref="canvas" class="sci-fi-background"></canvas>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

const canvas = ref<HTMLCanvasElement | null>(null);

onMounted(() => {
  const canvasEl = canvas.value;
  if (!canvasEl) return;

  const ctx = canvasEl.getContext('2d');
  if (!ctx) return;

  let width = (canvasEl.width = window.innerWidth);
  let height = (canvasEl.height = window.innerHeight);

  let particles: Particle[] = [];
  const particleCount = 100;

  class Particle {
    x: number;
    y: number;
    vx: number;
    vy: number;
    radius: number;
    color: string;

    constructor() {
      this.x = Math.random() * width;
      this.y = Math.random() * height;
      this.vx = Math.random() * 0.4 - 0.2;
      this.vy = Math.random() * 0.4 - 0.2;
      this.radius = Math.random() * 1.5 + 0.5;
      this.color = 'rgba(150, 150, 180, 0.5)';
    }

    update() {
      this.x += this.vx;
      this.y += this.vy;

      if (this.x < 0 || this.x > width) this.vx *= -1;
      if (this.y < 0 || this.y > height) this.vy *= -1;
    }

    draw() {
      ctx!.beginPath();
      ctx!.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
      ctx!.fillStyle = this.color;
      ctx!.fill();
    }
  }

  function init() {
    particles = [];
    for (let i = 0; i < particleCount; i++) {
      particles.push(new Particle());
    }
  }

  function animate() {
    ctx!.clearRect(0, 0, width, height);

    for (const particle of particles) {
      particle.update();
      particle.draw();
    }

    // Draw lines between nearby particles
    for (let i = 0; i < particles.length; i++) {
      for (let j = i + 1; j < particles.length; j++) {
        const dx = particles[i].x - particles[j].x;
        const dy = particles[i].y - particles[j].y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < 120) {
          ctx!.beginPath();
          ctx!.moveTo(particles[i].x, particles[i].y);
          ctx!.lineTo(particles[j].x, particles[j].y);
          ctx!.strokeStyle = `rgba(150, 150, 180, ${1 - distance / 120})`;
          ctx!.lineWidth = 0.5;
          ctx!.stroke();
        }
      }
    }

    requestAnimationFrame(animate);
  }

  const handleResize = () => {
    width = canvasEl.width = window.innerWidth;
    height = canvasEl.height = window.innerHeight;
    init();
  };

  window.addEventListener('resize', handleResize);

  init();
  animate();

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
});
</script>

<style scoped>
.sci-fi-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  opacity: 0.3;
}
</style>